package demo06;

import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author JYH
 * @version 1.0
 * @date 2022/11/1 15:51
 */
public class TestSafe02 {
    private static String[] arr = new String[2];
    public static int index=0;
    private static Object lock=new Object();
    public static void main(String[] args) throws Exception{
        Lock lock = new ReentrantLock();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    lock.lock();
                    if (arr[index] == null) {
                        arr[index] = "hello";
                        index++;
                    }
                }finally {
                    lock.unlock();
                }

            }

        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    lock.lock();
                    if (arr[index] == null) {
                        arr[index] = "world";
                        index++;
                    }
                }finally {
                    lock.unlock();
                }
            }
        });
        t1.start();
        t2.start();

        t1.join();
        t2.join();
        System.out.println(Arrays.toString(arr));
    }
}
